package name.hankc.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;

import name.hankc.spring.bean.Cat;
import name.hankc.spring.bean.Dog;

public class LazyLookupApplication {

  public static void main(String[] args) throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("basic_dl/quickstart-lazylookup.xml");
    Cat cat = ctx.getBean(Cat.class);
    System.out.println(cat);
    // 下面的代码会报Bean没有定义 NoSuchBeanDefinitionException
    // Dog dog = ctx.getBean(Dog.class);

    // 这一行代码不会报错
    ObjectProvider<Dog> dogProvider = ctx.getBeanProvider(Dog.class);
    // 1
    // Dog dog = dogProvider.getIfAvailable();
    // if (dog == null) {
    // dog = new Dog();
    // }
    // 2
    Dog dog = dogProvider.getIfAvailable(() -> new Dog());
    // 3
    // Dog dog = dogProvider.getIfAvailable(Dog::new);
    System.out.println(dog);
  }
}